#include "mkfilesettings.h"
#include <QFile>

#include <QDebug>

MKFileSettings::MKFileSettings(const QString &fileName) : QDomDocument(), MKSettings(), mFilename(fileName), mLastError(""), mIsValid(false)
{
	QFile file( mFilename);

	if(! file.exists())
	{
		mIsValid = false;
		mLastError = "*** SETTINGS: Конфигурационный файл " + mFilename + " не существует.";
		qDebug() << mLastError;
		return;
	}

	if(! file.open( QIODevice::ReadOnly))
	{
		mIsValid = false;
		mLastError = "*** SETTINGS: Ошибка открытия файла " + mFilename + " - " + file.errorString();
		qDebug() << mLastError;
		return;
	}


	QString errorMsg = "";
	int errLine = -1;
	int errCol = -1;
	if(! setContent( &file, &errorMsg, &errLine, &errCol ))
	{
		mIsValid = false;
		mLastError = "*** SETTINGS: Ошибка при чтении файла " + mFilename + " - " + errorMsg + "\n" + "Строка: " + QString::number(errLine)
				+ " Символ: " + QString::number(errCol);
		qDebug() << mLastError;
		return;
	}

	mRoot = documentElement();
	mIsValid = true;
}

MKFileSettings::~MKFileSettings()
{

}

bool MKFileSettings::save()
{
	QFile file( mFilename );
	if(!file.open( QIODevice::WriteOnly | QIODevice::Truncate ))
	{
		qDebug()<<"*** SETTINGS: Ошибка при открытии файла "<<mFilename;
		mLastError = "*** SETTINGS: Ошибка при открытии файла "+ mFilename + " " + file.errorString();
		return false;
	}

	file.write(toByteArray());

	return true;
}

QString MKFileSettings::typeRuName(const quint8 &typeId)
{
	QString result = "нет";
	QDomElement elType = type(typeId);
	if (!elType.isNull())
	{
		result = elType.attribute("ru_name", "нет");
	}
	return result;
}

QString MKFileSettings::categoryRuName(const quint8 &typeId, const quint8 &categoryId)
{
	QString result = "нет";
	QDomElement elCategory = category(typeId, categoryId);
	if (!elCategory.isNull())
	{
		result = elCategory.attribute("ru_name", "нет");
	}
	return result;
}

QList<quint8> MKFileSettings::categoriesByType(const quint8 &typeId)
{
	QList<quint8> result;
	QDomElement elType = type(typeId);
	if (elType.isNull() || !elType.hasChildNodes())
	{
		return result;
	}

	for(int i = 0; i<elType.elementsByTagName("category").count(); ++i)
	{
		QDomElement elCategory = elType.elementsByTagName("category").at(i).toElement();
		quint8 categoryId = static_cast<quint8>(elCategory.attribute("id").toUInt());
		result << categoryId;
	}

	return result;
}

QList<QPair<quint8, QString> > MKFileSettings::typesParameters()
{
	QList<QPair<quint8, QString> > result;
	for(int i = 0; i<mRoot.elementsByTagName("type").count(); ++i)
	{
		QDomElement elType = mRoot.elementsByTagName("type").at(i).toElement();

		quint8 typeId = static_cast<quint8>(elType.attribute("id", QString::number(i)).toUInt());
		QString typeRuName = elType.attribute("ru_name", "нет");

		result << qMakePair(typeId, typeRuName);
	}

	return result;
}

QList<QPair<quint8, QString> > MKFileSettings::typeCategoriesParameters(const quint8 &typeId)
{
	QList<QPair<quint8, QString> > result;
	QDomElement elType = type(typeId);
	if (elType.isNull() || !elType.hasChildNodes())
	{
		return result;
	}

	for(int i = 0; i<elType.elementsByTagName("category").count(); ++i)
	{
		QDomElement elCategory = elType.elementsByTagName("category").at(i).toElement();
		quint8 categoryId = static_cast<quint8>(elCategory.attribute("id").toUInt());
		QString categoryRuName = elCategory.attribute("ru_name", "нет");

		result << qMakePair(categoryId, categoryRuName);
	}

	return result;
}

bool MKFileSettings::addCategory(const quint8 &typeId, const QString &categoryRuName, const QString &categoryEngName)
{
	QDomElement elType = type(typeId);
	if (elType.isNull())
	{
		return false;
	}

	QDomElement elValue = QDomDocument::createElement("category");
	elValue.setAttribute("id", elType.elementsByTagName("category").count() + 1);
	elValue.setAttribute("name", categoryEngName);
	elValue.setAttribute("ru_name", categoryRuName);


	elValue = elType.appendChild(elValue).toElement();
	if (elValue.isNull())
	{
		return false;
	}

	return save();
}

QMap<QString, QString> MKFileSettings::databaseParameters()
{
	QMap<QString, QString> result;
	QDomElement elDatabase = database();
	if (elDatabase.isNull() || !elDatabase.hasChildNodes())
	{
		return result;
	}
	QString name;
	QString value;

	for (int i=0; i < elDatabase.elementsByTagName("parameter").count(); ++i)
	{
		QDomElement elParameter = elDatabase.elementsByTagName("parameter").at(i).toElement();
		name = elParameter.attribute("name");
		value = elParameter.attribute("value");

		result[name] = value;
	}
	return result;
}

QDomElement MKFileSettings::type(quint8 typeId)
{
	QDomElement result;
	for(int i = 0; i<mRoot.elementsByTagName("type").count(); ++i)
	{
		QDomElement elType = mRoot.elementsByTagName("type").at(i).toElement();
		if( elType.attribute("id").toUInt() == typeId)
		{
			result = elType;
			break;
		}
	}

	return result;
}

QDomElement MKFileSettings::category(quint8 typeId, quint8 categoryId)
{
	QDomElement result;
	QDomElement elType = type(typeId);
	if (elType.isNull() || !elType.hasChildNodes())
	{
		return result;
	}

	for(int i = 0; i<elType.elementsByTagName("category").count(); ++i)
	{
		QDomElement elCategory = elType.elementsByTagName("category").at(i).toElement();
		quint8 id = static_cast<quint8>(elCategory.attribute("id").toUInt());
		if( id == categoryId )
		{
			result = elCategory;
			break;
		}
	}
	return result;
}

QDomElement MKFileSettings::database()
{
	QDomElement result = mRoot.elementsByTagName("database").at(0).toElement();

	return result;
}
